08. CursorLoader Automatically Loading
CursorLoading Automatically Loading
This tutorial that shows notifyChange() call
Cursor setNotificationUri() method
Loader Automatically Reloads with Latest Data
Task Description:
In PetProvider.java:
Task Feedback:
Nice work! See our full explanation below.
Quiz Solution Explanation
Link to Solution Code
Previously, I already showed you setting up the notification uri and the insert method. Setting up the update and delete methods aren’t much different.
Setting Up the update Method
Since we actually update the pet information in updatePet() rather than update(), let's look there. I first check that something was actually updated by seeing the number of rows changed:
// Perform the update on the database and get the number of rows affected
int rowsUpdated = database.update(PetEntry.TABLE_NAME, values, selection, selectionArgs);
If it was more than zero, I call notifyChange:
// If 1 or more rows were updated, then notify all listeners that the data at the
// given URI has changed
if (rowsUpdated != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
Lastly, updatePet() will return the number of rows that were updated.
// Return the number of rows updated
return rowsUpdated;
Setting Up the delete Method
The process is similar for delete. I first check that something was actually delete by seeing the number of rows changed:
// Track the number of rows that were deleted
int rowsDeleted;
...
// Delete all rows that match the selection and selection args
// For case PETS:
rowsDeleted = database.delete(PetEntry.TABLE_NAME, selection, selectionArgs);
...
// For case PET_ID:
// Delete a single row given by the ID in the URI
rowsDeleted = database.delete(PetEntry.TABLE_NAME, selection, selectionArgs);
If it was more than zero, I call notifyChange:
// If 1 or more rows were deleted, then notify all listeners that the data at the
// given URI has changed
if (rowsDeleted != 0) {
getContext().getContentResolver().notifyChange(uri, null);
Lastly, delete() will return the number of rows that were delete:
// Return the number of rows deleted
return rowsDeleted;